import React, { useEffect, useState } from "react";
import { NavBar, Card, IndexBar, List, Tag, SearchBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import http from "../../api/http";
import useDebounce from "../../hooks/useDebounce";
function Index() {
  const navigate = useNavigate();
  const [citylist, setCityList] = useState([]);
  const [hotlist, sethotlist] = useState([]);
  const [SearchList, setSearchList] = useState([]);
  const getcitylist = async () => {
    const res = await http.get("/api/city");
    const { data, code } = res.data;
    console.log(data);
    if (code === 200) {
      setCityList(data.city);
      sethotlist(data.hotCities);
    }
  };
  useEffect(() => {
    getcitylist();
  }, []);

  const handleToSearch = useDebounce(async (val) => {
    if (val !== "") {
      const res2 = await http.get("/api/city/search", { params: { wd: val } });
      const { data, code } = res2.data;
      console.log(data);
      if (code === 200) {
        setSearchList(data);
      }
    }
  }, 800);
  return (
    <div>
      <NavBar onBack={() => navigate("/")}>城市列表</NavBar>
      <SearchBar placeholder="请输入内容" onChange={handleToSearch} />
      <List>
        {SearchList.map((item, index) => (
          <List.Item key={index} onClick={() => navigate("/")}>
            {item.name}
          </List.Item>
        ))}
      </List>
      <Card title="热门城市">
        {hotlist?.map((item, ind) => (
          <Tag
            key={ind}
            color="warning"
            style={{ margin: 12 }}
            onClick={() => navigate("/")}
          >
            {item.name}
          </Tag>
        ))}
      </Card>
      <Card title="城市列表">
        <div style={{ height: window.innerHeight }}>
          <IndexBar>
            {citylist.map((group) => {
              const { initial, list } = group;
              return (
                <IndexBar.Panel
                  index={initial}
                  title={`${initial}`}
                  key={`${initial}`}
                >
                  <List>
                    {list.map((item, index) => (
                      <List.Item key={index} onClick={() => navigate("/")}>
                        {item.name}
                      </List.Item>
                    ))}
                  </List>
                </IndexBar.Panel>
              );
            })}
          </IndexBar>
        </div>
      </Card>
    </div>
  );
}

export default Index;
